package com.jay.nio.clazz;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.MappedByteBuffer;

public class MappedByteBufferCls {
	public static void main(String[] args) throws Exception {
//		File f = new File("D:/software/ProcessTimeoutExample.java");
		File f = new File("D:/software/jdk-7u2-windows-i586-demos.zip");
		ByteBuffer(f);
		MappedByteBuffer(f);
	}

	public static void ByteBuffer(File f) throws IOException {

		ByteBuffer byteBuf = ByteBuffer.allocate((int) f.length());

		FileInputStream fis = new FileInputStream(
				"D:/software/ProcessTimeoutExample.java");
		FileOutputStream fos = new FileOutputStream("out.txt");
		FileChannel fc = fis.getChannel();

		long timeStar = System.currentTimeMillis();// 得到当前的时间
		fc.read(byteBuf);// 1 读取
		long timeEnd = System.currentTimeMillis();// 得到当前的时间

		System.out.println("Read time :" + (timeEnd - timeStar) + "ms");
		timeStar = System.currentTimeMillis();
		fos.write(byteBuf.array());// 写入
		timeEnd = System.currentTimeMillis();

		System.out.println("Write time :" + (timeEnd - timeStar) + "ms");

		fos.flush();
		fc.close();
		fis.close();
	}

	public static void MappedByteBuffer(File f) throws IOException {

		FileInputStream fis = new FileInputStream(f);
		FileOutputStream fos = new FileOutputStream("out.txt");
		FileChannel fc = fis.getChannel();

		long timeStar = System.currentTimeMillis();// 得到当前的时间
		MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
				f.length());
		long timeEnd = System.currentTimeMillis();// 得到当前的时间

		System.out.println("Read time :" + (timeEnd - timeStar) + "ms");
		timeStar = System.currentTimeMillis();
		fos.getChannel().write(mbb);// 写入
		timeEnd = System.currentTimeMillis();

		System.out.println("Write time :" + (timeEnd - timeStar) + "ms");

		fos.flush();
		fc.close();
		fis.close();
	}

}
